
import Vue from 'vue';
import { onBeforeValidate4TakeBack, executeBeforeEvent, releaseWorkflow,getValidateInformData,getDoneInformData} from '@/entries/finish-list/api';
import * as Fiber from 'fiber';
// const matchRequestToken = '2532017219062743402';
const wfAjax = {
  getSecurityByUserId() {
    return callBackendMethod("WFAjax", "getSecurityByUserId", ...arguments);
  },
  getCaseState() {
    return callBackendMethod("WFAjax", "getCaseState", ...arguments);
  },
  updateTemplateList() {
    return callBackendMethod("WFAjax", "updateTemplateList", ...arguments);
  },
  canRepeal() {
    return callBackendMethod("WFAjax", "canRepeal", ...arguments);
  },
  lockWorkflow() {
    return callBackendMethod("WFAjax", "lockWorkflow", ...arguments);
  },
  executeBeforeEvent() {
    return callBackendMethod("WFAjax", "executeBeforeEvent", ...arguments);
  }
};
let workfowFlashDialog = null;
let wfDiagram_v;
const _wfctxPath = _ctxPath;
let loadingInstance = {
  init() { },
  close() { },
  show() { },
  empty:true,
};

const showLoading = () => {
  if (loadingInstance.empty) {
    //动态引入防止新建页面错误逻辑发送后出现转圈
    import(/* webpackChunkName: "chunk-loading" */ '@/utils/loading.js')
        .then(md => loadingInstance = md.loadingInstance)
    return;
  }
  loadingInstance.show();
}
/**
   * 工作流流程事件前端JS执行函数
   */
async function executeWorkflowBeforeEvent(options) {
  let {
    event, bussinessId, affairId, processTemplateId, processId, activityId, formData, appName, formAppId, viewId, formViewOperation, processXml, attribute, commentContent, is4List
  } = options;
  let context = new Object();
  context["event"] = event;
  context["formData"] = formData;
  context["mastrid"] = formData;
  context["processTemplateId"] = processTemplateId;
  context["processId"] = processId;
  context["currentActivityId"] = activityId;
  context["bussinessId"] = bussinessId;
  context["affairId"] = affairId;
  context["appName"] = appName;
  context["formAppId"] = formAppId;
  context["formViewOperation"] = formViewOperation;
  if (!is4List) {
    //待确定
    // context["matchRequestToken"] = matchRequestToken;
  }
  context["processXml"] = processXml;
  //待确定
  // context["currentNodeLast"] = $("#workflow_thisNodelast_input").val();
  if (!context["businessData"]) {
    context["businessData"] = new Object();
  }
  context["businessData"]["attribute"] = attribute;
  context["businessData"]["commentContent"] = commentContent;

  return await executeWorkflowBeforeEventJson(context, is4List);
};

/**
 * 处理前事件执行
 * @param param
 * param = {
      event :"",//执行的事件名
      formData : "", //表单数据id
      mastrid : "", //表单数据id
      processTemplateId : "",//流程的模板id
      processId : "", //流程id
      currentActivityId : "",//当前节点id
      bussinessId : "", //业务数据id(如:summaryId)
      affairId : "", //事项id
      appName : "", //所属分类(collaboration,edoc)
      formAppId : "",//表单id
      formViewOperation : "",//表单视图id
      processXml : "",//流程图
      selectTargetNodeId : "",//回退节点
      submitStyleAfterStepBack:"",//指定回退类型: 0:流程重走，1:提交给我
      businessData : {
              attribute:"",//态度
              commentContent:"",//意见
              stepBackType:"normal"//回退类型(normal：普通回退，specifyBack：指定回退，circleBack：环形回退) 默认为普通回退
              }
  	
    };
 * @returns
 */
async function executeWorkflowBeforeEventJson(param, is4List) {
  var defaultOptions = {
    event: "",//执行的事件名
    formData: "", //表单数据id
    mastrid: "", //表单数据id
    processTemplateId: "",//流程的模板id
    processId: "", //流程id
    currentActivityId: "",//当前节点id
    bussinessId: "", //业务数据id(如:summaryId)
    affairId: "", //事项id
    appName: "", //所属分类(collaboration,edoc)
    formAppId: "",//表单id
    formViewOperation: "",//表单视图id
    //待确定
    // matchRequestToken: matchRequestToken,
    processXml: "",//流程图
    //待确定
    // currentNodeLast: $("#workflow_thisNodelast_input").val(),
    selectTargetNodeId: "",//回退节点
    submitStyleAfterStepBack: "",//指定回退类型: 0:流程重走，1:提交给我
    businessData: {
      attribute: "",//态度
      commentContent: "",//意见
      stepBackType: "normal"//回退类型(normal：普通回退，specifyBack：指定回退，circleBack：环形回退)
    }

  };
  if (is4List) {
    // delete defaultOptions.matchRequestToken;
  }

  var param = $.extend(defaultOptions, param);

  if (param.processTemplateId == null || param.processTemplateId == ""
  ) {
    return true;
  }
  var result = wfAjax.executeBeforeEvent(param.event, param);
  if (result) {
    //弱阻塞
    if (result.weakBlock) {
      if (confirm(result.alertMessage) == true) {
        //待确定
        releaseApplicationButtons();
        return true;
      } else {
        try {
          sendCount = 0;
          //待确定
          _initToolBarAndMoreToolBar && _initToolBarAndMoreToolBar();
          proce && proce.close && proce.close();
        } catch (e) { };
        return false;
      }
    } else if (result.alertMessage) {
      $.alert({
        'msg': result.alertMessage
      });
      try {
        //待确定
        releaseApplicationButtons();//回调
      } catch (e) { }
      return false;
    }
  }
  return true;
}

let _count = 0;
function releaseApplicationButtons() {
  _count = 0;
};

function beforeSubmit(affairid, attitude, content, object, sucessCallback, failedCallBack = () => { }, isExecute) {
  //isExecute 用来判断是否需要执行dee任务，如果多人执行，不是最后一个节点，或者竞争执行不是第一个处理，那就不执行
  if (validataDeeFormDev(affairid, attitude, failedCallBack)) {
    const taskType = callBackendMethod("formBindExtendClassEventListener", "achieveTaskType", affairid, attitude, content, isExecute);
    if (taskType) {
      let ds1;
      if ("ext" == taskType) {	//开发高级-扩展类
        ds1 = callBackendMethod("formBindExtendClassEventListener", "preHandler", affairid, attitude, content);
        if (ds1 && typeof (ds1) == "object") {
          if (ds1[0] == '1') {	//数组下标[0]值为1代表扩展类，数组下标[0]值2代表DEE，有返回代表审核失败，返回null代表正常
            if (object != null) {
              object.close();
            }
            var extContent = ds1[1].replace(/[\r\n]/g, "");	//扩展类返回值
            var dialog = $.dialog({
              url: "/seeyon/genericController.do?ViewPage=ctp/form/design/eventTip&content="
                + encodeURIComponent(extContent),
              title: "审核结果",
              width: 300,
              height: 300,
              closeParam: { show: false },
              buttons: [
                {
                  text: "转审核意见",
                  id: "sure1",
                  handler: function () {
                    if (content != "") {
                      content = content + "\r\n" + "-----------------------------" + "\r\n";
                    }
                    setContentDealComment(content + extContent);
                    failedCallBack();
                    dialog.close();
                  }
                },
                {
                  text: "取消",
                  id: "exit1",
                  handler: function () {
                    failedCallBack();
                    dialog.close();
                  }
                }
              ]
            });
          }
        } else {
          sucessCallback();
        }
      } else if ("dee" == taskType) {
        if (!window._hasPlugin("dee")) {
          Fiber.message.warning($.i18n('dee.form.hasplugin.off'));
          failedCallBack();
          return;
        }
        executeDeeTask(null, affairid, attitude, content, null, "false", sucessCallback, failedCallBack);
      } else {
        sucessCallback();
      }
    } else {
      sucessCallback();
    }
  }
}
function validataDeeFormDev(affairid, attitude, failedCallBack) {
  let flag = true;
  if (attitude == "start") {
    flag = callBackendMethod("formBindExtendClassEventListener", "validataDeeFormDev", affairid, attitude);
    if (!flag) {
      const dialog2 = $.messageBox({
        'title': '失败信息',
        'type': 100,
        'msg': '开发高级dee任务与内存不一致,请联系管理员检查表单配置！',
        'imgType': 1,
        buttons: [{
          id: 'exit1',
          text: "关闭",
          handler: function () {
            failedCallBack();
            dialog2.close();
          }
        }],
        close_fn: function () {
          failedCallBack();
          dialog2.close();
        }
      });
    }
  }
  return flag;
}
function executeDeeTask(r, affairid, attitude, content, currentEventId, skipConcurrent, sucessCallback, failedCallBack) {
  //var ds1 = r.preDeeHandler(affairid, attitude, content, currentEventId, skipConcurrent);
  var ds1 = callBackendMethod("collaborationFormBindEventListener", "preDeeHandler", affairid, attitude, content, currentEventId, skipConcurrent);
  if (ds1) {
    var blockFormWriteBackJson = ds1["blockFormWriteBackJson"];
    if (blockFormWriteBackJson) {
      var objs = blockFormWriteBackJson;
      // 兼容google浏览器需要下面这一句替换掉google浏览器添加的pre
      objs = objs.replace("<pre style=\"word-wrap: break-word; white-space: pre-wrap;\">", "").replace("</pre>", "").replace("<pre>", "");
      var _objs = $.parseJSON(objs);
      if (_objs.success == "true" || _objs.success == true) {
        // 如果当前权限因为高级权限改变，则将改变后的权限id记录在页面中
        if (_objs.viewRight != undefined && $("#rightId").val() != _objs.viewRight) {
          $("#rightId").val(_objs.viewRight);
          $("#img").removeClass("hidden").addClass("hidden");
        }
        _objs = _objs.results;
        if (typeof formCalcResultsBackFill != "undefined") {
          formCalcResultsBackFill(_objs);
        } else if (document.getElementById("zwIframe") != null) {
          document.getElementById("zwIframe").contentWindow.formCalcResultsBackFill(_objs);
        } else {
          document.zwIframe.formCalcResultsBackFill(_objs);
        }
        //      formCalcResultsBackFill(_objs);
      } else {
        Fiber.message.warning(_objs.errorMsg);
      }
    }

    var hasNext = ds1["hasNext"];
    var retSkipConcurrent = ds1["skipConcurrent"];
    var retCurrentEventId = ds1["currentEventId"];
    var blockInfoMsgType = ds1["blockInfoMsgType"];
    var blockInfoReason = ds1["blockInfoReason"];
    var exception = ds1["exception"];
    if (exception) {
      var dialog2 = $.messageBox({
        'title': '失败信息',
        'type': 100,
        'msg': exception,
        'imgType': 1,
        buttons: [{
          id: 'exit1',
          text: "关闭",
          handler: function () {
            if (failedCallBack && failedCallBack != "undefined") {
              failedCallBack();
            }
            dialog2.close();
          }
        }],
        close_fn: function () {
          if (failedCallBack && failedCallBack != "undefined") {
            failedCallBack();
          }
          dialog2.close();
        }
      });
    } else if (blockInfoMsgType == "error") {
      var dialog1 = $.messageBox({
        'title': '失败信息',
        'type': 100,
        'msg': blockInfoReason,
        'imgType': 1,
        buttons: [{
          id: 'exit1',
          text: "关闭",
          handler: function () {
            if (failedCallBack && failedCallBack != "undefined") {
              failedCallBack();
            }
            dialog1.close();
          }
        }],
        close_fn: function () {
          if (failedCallBack && failedCallBack != "undefined") {
            failedCallBack();
          }
          dialog1.close();
        }
      });
    } else if (blockInfoMsgType == "info") {
      var dialog = $.messageBox({
        'title': '提示信息',
        'type': 100,
        'msg': blockInfoReason,
        'imgType': 0,
        buttons: [{
          id: 'exit1',
          text: "确定",
          handler: function () {
            if (hasNext == "true") {
              executeDeeTask(null, affairid, attitude, content, retCurrentEventId, retSkipConcurrent, sucessCallback, failedCallBack);
            } else {
              sucessCallback();
            }
            dialog.close(dialog.index);
          }
        }],
        close_fn: function () {
          if (hasNext == "true") {
            executeDeeTask(null, affairid, attitude, content, retCurrentEventId, retSkipConcurrent, sucessCallback, failedCallBack);
          } else {
            sucessCallback();
          }
          dialog.close(dialog.index);
        }
      });
    } else {
      if (hasNext == "true") {
        executeDeeTask(null, affairid, attitude, content, retCurrentEventId, retSkipConcurrent, sucessCallback, failedCallBack);
      } else {
        sucessCallback();
      }
    }
  }
}
/**
 * 解除流程锁
 */
function releaseWorkflowByAction(processId, currentUserId, action) {
  //待确定loading
  // var Loading = null;
  // if (typeof CtpUiLoading != "undefined") {
  //   Loading = new CtpUiLoading({ styleType: "3" });
  // }
  const params = `managerMethod=releaseWorkflow&arguments=${JSON.stringify([processId, currentUserId, action])}`;
  releaseWorkflow(params).then(res => {
    console.log('releaseWorkflow', res);
  });
  // if (Loading) {
  //   Loading.close();
  // }
}
function getAffairState(affairId) {
  return callBackendMethod("colManager", "getAffairState", affairId);
}
function SecretCheck(result, operate) {
  this.secretCheckResult = result;
  this.operate = operate;

  SecretCheck.prototype.getOperate = function () {
    return this.operate;
  };

  SecretCheck.prototype.getSuccessAffairIds = function () {
    var affairIdArray = new Array();

    for (var i = 0; i < this.secretCheckResult.length; i++) {
      if (this.secretCheckResult[i].resultCode === 0) {
        affairIdArray.push(this.secretCheckResult[i].affairId);
      }
    }

    return affairIdArray;
  };

  SecretCheck.prototype.messageDialog = function (callback) {
    var ur1 = _ctxPath + "/collaboration/batchController.do?method=secretBatch";
    var dialog1 = $.dialog({
      url: ur1,
      title: $.i18n('common.system.hint.label'),
      //系统提示
      width: 450,
      height: 310,
      targetWindow: getCtpTop(),
      isDrag: true,
      transParams: this,
      buttons: [{
        text: $.i18n('common.button.close.label'),
        //关闭
        handler: function handler() {
          dialog1.close();

          if (callback) {
            callback();
          }
        }
      }],
      closeParam: {
        show: true,
        handler: function handler() {
          dialog1.close();

          if (callback) {
            callback();
          }
        }
      },
      minParam: {
        show: false
      },
      maxParam: {
        show: false
      }
    });
  };

  SecretCheck.prototype.size = function () {
    return this.secretCheckResult.length;
  };

  SecretCheck.prototype.getCancelData = function () {
    var result = new ArrayList();

    for (var i = 0; i < this.secretCheckResult.length; i++) {
      var ele = this.secretCheckResult[i];

      if (ele && ele.resultCode !== 0) {
        result.add(ele);
      }
    }

    return result;
  };
};
function showFlowChart(_contextCaseId, _contextProcessId, _templateId, _contextActivityId, bodyType, showHastenButton, dataType) {
  var isTemplate = false;
  if (_templateId && "undefined" != _templateId && "null" != _templateId) {
    isTemplate = true;
  }
  var showHisWorkflow = false;
  if (dataType == '1') {
    showHisWorkflow = true;
  }
  var options = {
    targetWin: getA8Top(),
    caseId: _contextCaseId,
    processId: _contextProcessId,
    isTemplate: isTemplate,
    showHastenButton: showHastenButton,
    appName: "collaboration",
    currentNodeId: _contextActivityId,
    isHistoryFlag: showHisWorkflow,
    scene: 3,
    SPK: 'freeFlow',
    NPS: 'default',
    canExePrediction: bodyType === '20' && $.ctx.hasPlugin("workflowAdvanced")
  };
  showDiagram(options);
}

/**
   * 
   * 打开流程编辑窗口
   * 
   * options = {
   *     targetWin : window,// Window对象， 必填， dialog弹层依赖对象
   *     valueWin : window,// Window对象， 非必填， 工作流值域所在window层级， 不传则同 targetWin
   *     embedIframeObj : iframe,//非dialong方式展现， 直接在当前页面展现的iframe
   *     
   *     appName : "collaboration",//模块名称
   *     
   *     processId : "8873084409352242841",//流程模板ID， processId
   *     oldTemplateId : "8873084409352242841",//模板id， 目前只看到用来选择子流程时过滤自己
   *     
   *     defaultPolicyId : "collaboration", //默认节点权限ID
   *     defaultPolicyName : "协同",//默认节点权限名称
   *     
   *     currentUserId : "-7704680836011635710",//当前登录人员ID，
   *     currentUserName : "xuqw1+",//当前登录人员名称
   *     currentAccountName : "创世纪",//当前登录单位名称
   *     flowPermAccountId ： "-5546493497148422300",//节点权限校验单位ID，目前只有公文有用
   *     
   *     formAppId : "8153854480052077855",//单据ID、表单或者公文单ID
   *     startDefualtRightId : "-7761117042121225097.-6350791176455829286",//表单开始节点默认节点权限
   *     normalDefualtRightId : "-7761117042121225097.814211044810834268",//表单普通节点默认节点权限
   *     
   *     wendanId : "",//公文文单ID
   *     isValidate ： true,//是否需要校验，流程复制的时候
   *     canCopyFlow : 是否能复制流程
   *     selectPeopleExtParams ： ""//选人组件自定义扩展参数
   *     scene : 0|1|2|3|4|5|6;// 设计态[0]:编辑模版流程(单位管理员、表单管理员) |设计态[1]:自由流程(普通人员)
   *     						  |设计态[2]:查看模版流程(普通人员)|运行态[3]:查看(普通人员)
   *     						  |运行态[4]:督办(督办人员)|运行态[5]:管控(管理人员)|[6]指定回退flash显示页面
   *     caseId : "" ,
   *     currentNodeId : "-1111" 当前节点ID,
   *     formMutilOprationIds:"",
   *     showHastenButton : false, 是否显示催办按钮
   *     isHistoryFlag : "true"/"false" 是否是分库的数据
   *     superviseId : "" 
   *     isAdminMangerModel ： true/false 是否是流程管理的页面
   *	 buttons : [{id:"close",callBackFn:function(){}},//数组，显示的按钮
   * 				{id:"cancel",callBackFn:function(){}}, 
   *				{id:"modify",callBackFn:function(){}}，
   * 				{id:"ok",callBackFn:function(){}}， 
   *				{id:"repeal",callBackFn:function(){}}，
   * 				{id:"stop",callBackFn:function(){}}
   * 				{id:"saveDBOK",callBackFn:function(){}}]  //直接保存修改后的信息
   * 
   * 	isSkipNode : 是否是跳过节点模式；
   * 	callBackFn 
   * }
   */
function showDiagram(options) {
  // 兼容查不到window
  if (!options.valueWin) {
    options.valueWin = window;
  }
  var defaultOptions = {
    /*targetWin : getCtpTop(),
    valueWin : getCtpTop(),*/
    isModalDialog: true,
    isHistoryFlag: false,
    isDebugger: false,
    scene: 3,
    caseId: "",
    san: "",
    currentNodeId: "",
    formMutilOprationIds: "",
    showHastenButton: false,
    selectPeopleExtParams: "",
    isTemplate: false,
    targetWin: null,
    valueWin: null,
    title: $.i18n('common.design.workflow.label'), // 编辑流程
    flowPermAccountId: "",
    defaultPolicyId: "",
    defaultPolicyName: "",
    buttons: [{ "id": "close" }], // 默认关闭按钮
    superviseId: "",
    SPK: "default",
    NPS: "default",
    currentUserId: "",
    currentUserName: "",
    masterId: "",
    formAppId: "",
    isAdminMangerModel: false,
    canExePrediction: false,// 是否可以执行流程预测
    needClonedProcessId: "",
    isSkipNode: "false", //是否是跳过节点模式,
    canSetCircleBranch: "true",// 是否允许设置环形流程
    callBackFn: null,
    isCIPModel: false,
    verifyResultXml: "",//校验结果的xml
    immediatelySave: false,
    onlyEditSubProcess: false,
    disableEditSubprocess: false
  };
  defaultOptions.targetWin = getCtpTop();
  defaultOptions.valueWin = getCtpTop();

  // 浏览态，如果没有传参，显示"查看流程图"
  var isView = false;
  if (options.scene == 2 || options.scene == 3) { // 浏览
    isView = true;
  }

  // 根据业务逻辑初始化部分参数
  initParam4Diagram(options, isView);

  var options = $.extend(defaultOptions, options);

  // 窗口校验
  _closeFlashDialogBeforeOpen(options.targetWin);

  //待确定
  var wf_v = wfAjax.getSecurityByUserId("");
  if (wf_v) {
    wfDiagram_v = wf_v;
  }

  // 为了解决dialog延迟关闭及IE8关闭问题，采用延迟打开窗口的方式
  setTimeout(
    function () {

      var dwidth = $(options.targetWin).width();
      var dheight = $(options.targetWin).height();
      if (dwidth <= 0 || dheight <= 0) {
        dwidth = $(document.body).width();
        dheight = $(document.body).height();
      }

      var myUrl = _wfctxPath
        + '/workflow/designer.do?method=showDiagram';
      myUrl += '&isDebugger=' + options.isDebugger;
      myUrl += '&isModalDialog=' + options.isModalDialog;
      myUrl += '&isTemplate=' + options.isTemplate;
      myUrl += '&formApp=' + (options.formAppId || "");
      myUrl += '&appName=' + options.appName;
      myUrl += '&san=' + options.san;
      myUrl += '&processId=' + options.processId;
      myUrl += '&currentUserId=' + options.currentUserId || window._wfcurrentUserId || "";
      myUrl += '&currentUserName=' + encodeURIComponent(options.currentUserName);
      myUrl += '&currentUserAccountName=' + encodeURIComponent(options.currentAccountName);
      myUrl += '&defaultPolicyId=' + encodeURIComponent(options.defaultPolicyId);
      myUrl += '&defaultPolicyName=' + encodeURIComponent(options.defaultPolicyName);
      myUrl += '&flowPermAccountId=' + options.flowPermAccountId;
      myUrl += '&wendanId=' + (options.wendanId || "-1");
      myUrl += '&isvalidate=false&oldPTId='
        + (options.oldTemplateId == undefined ? ""
          : options.oldTemplateId);
      myUrl += '&startFormViewOperation='
        + options.startDefualtRightId;
      myUrl += '&nodeFormViewOperation='
        + options.normalDefualtRightId;
      myUrl += '&needValidate=' + options.isValidate;
      myUrl += '&canCopyFlow=' + options.canCopyFlow;
      myUrl += '&isHistoryFlag=' + options.isHistoryFlag;
      myUrl += '&caseId=' + options.caseId;
      myUrl += '&currentNodeId=' + options.currentNodeId;
      myUrl += '&formMutilOprationIds='
        + options.formMutilOprationIds;
      myUrl += '&showHastenButton=' + encodeURIComponent(options.showHastenButton);
      myUrl += '&superviseId=' + options.superviseId;
      myUrl += '&selectPeopleExtParams=' + options.selectPeopleExtParams;
      myUrl += '&SPK=' + options.SPK;
      myUrl += '&NPS=' + options.NPS;
      myUrl += '&masterId=' + options.masterId;
      myUrl += '&canExePrediction=' + options.canExePrediction;
      myUrl += '&needClonedProcessId=' + options.needClonedProcessId;
      myUrl += '&CWID=' + options.currentWorkitemId;
      myUrl += '&SD=' + options.splitDisplay;
      myUrl += '&isSkipNode=' + options.isSkipNode;
      myUrl += '&canSetCircleBranch=' + options.canSetCircleBranch;
      myUrl += '&v=' + wfDiagram_v;
      myUrl += '&isCIPModel=' + options.isCIPModel;
      myUrl += '&onlyEditSubProcess=' + options.onlyEditSubProcess;
      myUrl += '&disableEditSubprocess=' + options.disableEditSubprocess;

      var isAdminMangerModel = options.isAdminMangerModel;
      if (!isAdminMangerModel) {
        isAdminMangerModel = options.scene == 5 || options.scene == 4; //管控态，会加锁，FALSH界面可以直接修改流程入库
      }
      if (isAdminMangerModel) {
        myUrl += "&addWorkflowExpirationTimeLock=true";

      }
      if (options.isSuperviseBatch) {
        myUrl += "&isSuperviseBatch=true";
      }
      var lockAction = 1;
      myUrl += '&action=' + lockAction;

      myUrl += CsrfGuard.getUrlSurffix();

      if (options.embedIframeObj) {// 页面嵌入模式
        myUrl += '&openFromIframe=true';
        myUrl += '&scene=' + options.scene;
        $(options.embedIframeObj).attr("src", myUrl);
        return;
      }

      var returnValueWindow = options.targetWin;
      if (options.valueWin) {
        returnValueWindow = options.valueWin;
      }

      var isButtonDisabled = false;
      var resultLock = ["", ""];
      var isLockTrue = false;  //是否真的加锁成功了
      if (isAdminMangerModel) {
        isButtonDisabled = false;
        var caseId = options.caseId;
        var currentUserId = (options.currentUserId || window._wfcurrentUserId || "");
        if (!options.isSuperviseBatch) {//非批处理加锁
          isButtonDisabled = __lockWorkflow(caseId, isButtonDisabled, options.processId, currentUserId);
          if (!isButtonDisabled) {
            isLockTrue = true;
          }
        }
      }

      function __lockWorkflow(caseId, _isButtonDisabled, processId, currentUserId) {
        if (!caseId) {
          return false;
        }
        // 待确定
        var caseState = wfAjax.getCaseState(caseId);
        _isButtonDisabled = caseState[0] == 'true' ? true : false;
        if (!_isButtonDisabled) {
          resultLock = lockWorkflowUseNowexpirationTime(processId, currentUserId, lockAction, "true");
          if (resultLock[0] == 'false') {
            _isButtonDisabled = true;
          }
        }
        return _isButtonDisabled;
      }

      //隐藏确定按钮的时候查看默认使用查看模式
      if (!isButtonDisabled) {
        myUrl += '&scene=' + options.scene;
      } else {
        myUrl += '&scene=3';
      }


      workfowFlashDialog = $
        .dialog({
          id: 'workflow_dialog_workflowDesigner_Id',
          isHide: true,
          url: myUrl,
          width: dwidth - 20,
          height: dheight - 100,
          title: options.title,
          targetWindow: options.targetWin,
          transParams: {
            subProcessJson: $("#process_subsetting",
              returnValueWindow.document).val(),
            formId: $("#formId").val(),
            dwidths: dwidth,
            dheights: dheight - 20,
            processIdAndCaseIdAndFormAppIdAndMasterId: options.processIdAndCaseIdAndFormAppIdAndMasterId,
            templateSubject: options.templateSubject,
            workflowRule: $("#process_rulecontent",
              returnValueWindow.document).val(),
            returnValueWindow: returnValueWindow,
            callBackFn: options.callBackFn,
            modifyTotal: options.modifyTotal,
            verifyResultXml: options.verifyResultXml,
            accessFileSecretLevel: options.accessFileSecretLevel,
            openForecastParam: {
              formId: $("#formId").val(),//待确定
              templateId: window.systemTemplateId || window.templateId,
              processId: options.processId,
              currentNodeId: options.currentNodeId,
              summaryId: window.summaryId,//待确定
              _executePrediction: window._executePrediction//待确定
            }
          },
          closeParam: {
            'show': true,
            handler: function () {
              /*if (typeof recoverWorkFlowHistoryData == 'function') {
                recoverWorkFlowHistoryData();
              }*/
              if (isLockTrue) {
                if (!options.isSuperviseBatch) {//批处理解锁
                  //待确定
                  releaseWorkflowByAction(options.processId, (options.currentUserId || window._wfcurrentUserId || ""), 1);
                }
              }

            }
          },
          minParam: {
            show: false
          },
          maxParam: {
            show: false
          },
          notCopyReturnValue: true,
          buttons: assembleButtons(options, isButtonDisabled, isLockTrue)
        });

      if (resultLock && resultLock[0] && resultLock[0] == 'false') {
        Fiber.message.warning(resultLock[1]);
      }

    }, 10);
}
function getBtn(buttons, key) {
  if (buttons) {
    for (var i = 0; i < buttons.length; i++) {
      var btn = buttons[i];
      if (btn.id == key) {
        return btn;
      }
    }
  }
  return null;
}
//组装流程图显示的button
function assembleButtons(options, isButtonDisabled, isLockTrue) {

  var diagramButtons = [];

  if (options.isSkipNode === "true") { //跳过节点的时候，不需要按钮;
    return diagramButtons;
  }

  var modifyBtn = getBtn(options.buttons, "modify");
  var repealBtn = getBtn(options.buttons, "repeal");
  var stopBtn = getBtn(options.buttons, "stop");
  var cancelBtn = getBtn(options.buttons, "cancel");
  var okBtn = getBtn(options.buttons, "ok");
  var closeBtn = getBtn(options.buttons, "close");
  var saveDBOKBtn = getBtn(options.buttons, "saveDBOK");
  var saveDBOKBtnHide = false;
  if (modifyBtn) {
    var saveDBOKBtnHide = true;
    var modifyButton = {
      id: 'modifyButton',
      text: $.i18n('common.toolbar.update.label'),
      isEmphasize: true,
      disabled: isButtonDisabled,
      handler: function () {
        var returnValue = workfowFlashDialog.getReturnValue({
          "innerButtonId": "supervious_modify"
        });
        if (returnValue) {

          workfowFlashDialog.showBtn("saveDBOKButton");
          workfowFlashDialog.hideBtn("modifyButton");
          workfowFlashDialog.disabledBtn("repealButton");
          workfowFlashDialog.disabledBtn("stopButton");

          if (typeof modifyBtn.callBackFn == "function") {
            modifyBtn.callBackFn(options, workfowFlashDialog);
          }
        }
      }
    };
    diagramButtons.push(modifyButton);

  }
  if (saveDBOKBtn || modifyBtn) {
    var text = $.i18n('common.button.ok.label');
    if (options.isSuperviseBatch) {
      text = $.i18n('workflow.designer.page.button.supervise.batch.modify.ok.js');
    }
    var saveDBOKButton = {
      id: 'saveDBOKButton',
      hide: saveDBOKBtnHide,
      btnType: 1,
      isEmphasize: true,
      disabled: isButtonDisabled,
      text: text,
      handler: function () {
        var returnValue = workfowFlashDialog.getReturnValue({
          "innerButtonId": "supervious_ok"
        });

        if (isLockTrue) {
          _releaseLock(options);
        }

        if (returnValue) {

          // 关闭dialog窗口
          _closeOrHideFlashDialog();


          if (saveDBOKBtn && typeof saveDBOKBtn.callBackFn == "function") {
            saveDBOKBtn.callBackFn(returnValue);
          }
        } else {
          // 关闭dialog窗口
          _closeOrHideFlashDialog();
        }
      }
    };
    diagramButtons.push(saveDBOKButton);
  }

  if (repealBtn) {
    var repealButton = {
      id: 'repealButton',
      text: $.i18n('common.toolbar.repeal.label'),
      disabled: isButtonDisabled,
      handler: function () {
        var crResult = canRepeal(options.appName, options.processId, "");
        if (crResult[0] == 'false') {
          Fiber.message.warning(crResult[1]);
          return;
        }

        if (typeof repealBtn.callBackFn == "function") {
          repealBtn.callBackFn(options, workfowFlashDialog);
        }
      }
    };
    diagramButtons.push(repealButton);
  }

  if (stopBtn) {
    var stopButton = {
      id: 'stopButton',
      text: $.i18n('workflow.designer.page.button.stop'),
      disabled: isButtonDisabled,
      handler: function () {

        if (typeof stopBtn.callBackFn == "function") {
          stopBtn.callBackFn(options, workfowFlashDialog);
        }
      }
    };

    diagramButtons.push(stopButton);
  }

  if (closeBtn) {
    var closeButton = {
      text: $.i18n('common.button.close.label'),
      handler: function () {

        // 关闭dialog窗口
        _closeOrHideFlashDialog();

        if (isLockTrue) {
          _releaseLock(options);
        }


        if (typeof closeBtn.callBackFn == "function") {
          closeBtn.callBackFn(options, workfowFlashDialog);
        }
      }
    };
    diagramButtons.push(closeButton);
  }

  if (okBtn) {
    var okButtons = {
      text: $.i18n('common.button.ok.label'),
      isEmphasize: true,
      handler: function () {

        function __callback(returnValue) {
          if (returnValue) {

            var beforeValidateResult = true;

            //点OK前校验
            if (typeof okBtn.beforeValidate == 'function') {
              beforeValidateResult = okBtn.beforeValidate();
            }

            if (!beforeValidateResult) {
              return;
            }

            if (options.immediatelySave == true) {

              var result = wfAjax.updateTemplateList(options.appName, options.NPS, returnValue[6], options.formApp, returnValue[1], returnValue[3]);
              if (result != null && !result.success) {
                Fiber.message.warning(result.msg);
                return;
              }

            } else {

              // 从flash流程设计器中获得流程xml内容
              var valueWindow = options.valueWin == null ? options.targetWin : options.valueWin;
              initDialogDataToParentPage(returnValue, valueWindow, options.targetWin);

            }


            // 关闭dialog窗口
            _closeOrHideFlashDialog();

            if (typeof finishWorkFlowModify == 'function') {
              finishWorkFlowModify();
            }

            try {// 协同快速选人
              window.distroy_token = true;// lilong
              // 这个时候屏蔽右侧的常用联系人
              //  编辑流程后，屏蔽常用联系人
              var parentTemplateSelTab = $("#templateSelTab");
              var parentPersonSel = $("#personSelArea");
              var parentTemplateSel = $("#tempateSelArea");
              var parentPersonSelTab = $("#personSelTab");
              if (parentPersonSelTab) {
                parentPersonSelTab.hide();
              }
              $(".common_contact_title .active").removeClass("active");

              if (parentTemplateSelTab && parentTemplateSel && parentPersonSel) {
                parentTemplateSelTab.addClass("active");
                parentPersonSel.hide();
                parentTemplateSel.show();
                loadRightTemplates();
              }
            } catch (e) {
              console.log(e);
            }

            if (typeof okBtn.callBackFn == "function") {
              okBtn.callBackFn(options, workfowFlashDialog);
            }

            if (isLockTrue) {
              releaseWorkflowByAction(options.processId,
                (options.currentUserId || window._wfcurrentUserId || ""), 1);
            }
          }
        }

        var returnValue = workfowFlashDialog.getReturnValue({
          "innerButtonId": "ok",
          "checkXML": options.immediatelySave == true,
          "checkCallback": __callback
        });

        if (returnValue) {
          __callback(returnValue);
        }
      }
    };
    diagramButtons.push(okButtons);
  }


  if (cancelBtn) {
    var cancelButtons = {

      text: $.i18n('common.button.cancel.label'),
      handler: function () {

        // 关闭dialog窗口
        _closeOrHideFlashDialog();

        if (typeof recoverWorkFlowHistoryData == 'function') {
          recoverWorkFlowHistoryData();
        }

        if (typeof cancelBtn.callBackFn == "function") {
          cancelBtn.callBackFn(options, workfowFlashDialog);
        }

        if (isLockTrue) {
          releaseWorkflowByAction(options.processId,
            (options.currentUserId || window._wfcurrentUserId || ""), 1);
        }
      }

    };
    diagramButtons.push(cancelButtons);
  }
  return diagramButtons;
}
/**
* @description 将弹出页面的数据初始化到父页面
* @returnValue 弹出页面返回的数据
*/
function initDialogDataToParentPage(returnValue, returnValueWindow, tWindow) {

  if (returnValueWindow == null) {
    returnValueWindow = tWindow;
  }

  var process_desc_by = returnValue[0];
  var process_xml = returnValue[1];
  var process_info = returnValue[2];
  var process_rulecontent = returnValue[3];
  var process_subsetting = returnValue[4];
  var process_event = returnValue[5];
  var process_properties = returnValue[7];

  var process_desc_by_input = $("#process_desc_by", returnValueWindow.document)[0];
  var process_xml_input = $("#process_xml", returnValueWindow.document)[0];
  var process_info_input = $("#process_info", returnValueWindow.document)[0];
  var process_rulecontent_input = $("#process_rulecontent", returnValueWindow.document)[0];
  var process_subsetting_input = $("#process_subsetting", returnValueWindow.document)[0];
  var process_event_input = $("#process_event", returnValueWindow.document)[0];
  var process_properties_input = $("#process_properties", returnValueWindow.document)[0];

  if (!process_desc_by_input && process_desc_by) {
    showFlashAlert("Error: not found process_desc_by input element in parent page!");
    throw new Error("Error: not found process_desc_by input element in parent page!");
  }
  if (!process_xml_input && process_xml) {
    showFlashAlert("Error: not found process_xml input element in parent page!");
    throw new Error("Error: not found process_xml input element in parent page!");
  }
  if (!process_info_input && process_info) {
    showFlashAlert("Error: not found process_info input element in parent page!");
    throw new Error("Error: not found process_info input element in parent page!");
  }
  if (!process_rulecontent_input && process_rulecontent) {
    alert("Error: not found process_rulecontent input element in parent page!");
    throw new Error("Error: not found process_rulecontent input element in parent page!");
  }
  if (!process_subsetting_input && process_subsetting) {
    showFlashAlert("Error: not found process_subsetting input element in parent page!");
    throw new Error("Error: not found process_subsetting input element in parent page!");
  }
  if (process_desc_by) {
    process_desc_by_input.value = process_desc_by;
  }
  if (process_xml) {
    process_xml_input.value = process_xml;
  }
  if (process_info) {
    $("#process_info", returnValueWindow.document).attr("value", process_info);
    $("#process_info", returnValueWindow.document).trigger("propertychange").trigger("input");


    try {
      $("#process_info", returnValueWindow.document).tokenInput("destroy");//lilong wangchw 0326
      //隐藏协同右侧的常用联系人
      if (typeof (hideCommonContact) != "undefined") {
        hideCommonContact();
      }

    } catch (e) { }
    $("#process_info", returnValueWindow.document).attr("value", process_info);
  }
  try {
    process_rulecontent_input.value = (process_rulecontent == undefined || process_rulecontent == null) ? "" : process_rulecontent;
  } catch (e) {
  }
  if (process_subsetting) {
    process_subsetting_input.value = process_subsetting;
  }
  if (process_event_input) {
    //alert(process_event);
    process_event_input.value = process_event;
  }
  if (process_properties_input) {
    process_properties_input.value = process_properties;
  }

  try {
    var tprocess_desc_by_input = $("#process_desc_by", tWindow.document)[0];
    var tprocess_xml_input = $("#process_xml", tWindow.document)[0];
    var tprocess_info_input = $("#process_info", tWindow.document)[0];
    var tprocess_rulecontent_input = $("#process_rulecontent", tWindow.document)[0];
    var tprocess_subsetting_input = $("#process_subsetting", tWindow.document)[0];
    var tprocess_event_input = $("#process_event", tWindow.document)[0];
    var tprocess_properties_input = $("#process_properties", tWindow.document)[0];

    tprocess_desc_by_input.value = process_desc_by;
    tprocess_xml_input.value = process_xml;
    tprocess_info_input.value = process_info;
    tprocess_rulecontent_input.value = process_rulecontent;
    tprocess_subsetting_input.value = process_subsetting;
    tprocess_event_input.value = process_event;
    tprocess_properties_input.value = process_properties;
  } catch (e) { }
}
function showFlashAlert(args) {
  try {
    var alert = $.alert(args);
    // alert(args);
  } catch (e) {
    alert(args);
  }
}
/**
   * 是否允许撤销
   * 返回值是一个js数组对象，有以下属性
   * String[0]:true表示可以回退;false表示不可以撤销
   * String[1]:如果不可以撤销，则这里表示为不能撤销的提示信息
   */
function canRepeal(appName, processId, nodeId) {
  try {
    // if ($("#workflow_node_condition_input")[0]) {
    //   $("#workflow_node_condition_input")[0].value = "{\"matchRequestToken\":\"" + matchRequestToken + "\"}";
    // }
    return wfAjax.canRepeal(appName, processId, nodeId);
  } catch (e) { alert(e.message); }
}
/** 关闭flash dialog窗口 * */
function _closeOrHideFlashDialog() {

  if (!$.browser.msie) {
    workfowFlashDialog.close();
  } else {
    workfowFlashDialog.hideDialog();
  }
}
function _releaseLock(options) {
  var currentUserId = (options.currentUserId || window._wfcurrentUserId || "");
  if (!options.isSuperviseBatch) {//非批处理解锁

    releaseWorkflowByAction(options.processId, currentUserId, 1);
  }
}
/**
   * 加流程锁
   * @processId:流程ID
   * @currentUserId:当前登录用户ID
   * @action:当前操作类型:
   *  -1: 默认修改正文或流程锁
   *  0:督办修改流程、1:单位管理员修改流程、2:发起者修改流程
   *  3:加签、4:减签、5:当前会签、6:知会、7:传阅、8:多级会签
   *  9：回退、10：指定回退、11：终止、12：撤销、13：取回
   *  14: preSendOrHandleWorkflow时
   *  15: 正文锁
   *  16: 附件锁
   * @param useNowexpirationTime,是否需要设置超时自动解锁，设置lock对象的expirationTime为当前时间("true"/"false")
   * 返回String[2]:String[0]:"true":表示加锁成功,"false":表示加锁失败;String[1]:当前占用锁的操作类型提示信息
   */
function lockWorkflowUseNowexpirationTime(processId, currentUserId, action, useNowexpirationTime) {
  try {
    if (useNowexpirationTime && useNowexpirationTime == "true") {
      useNowexpirationTime = "true";
    } else {
      useNowexpirationTime = "false";
    }
    // 待确定
    var result = wfAjax.lockWorkflow(processId, currentUserId, action, useNowexpirationTime);
    if (result == null) {
      result = new Array("false", $.i18n('workflow.wapi.exception.msg002'));
    }
    return result;
  } catch (e) { alert(e.message); }
}
// 根据业务逻辑初始化部分参数
function initParam4Diagram(options, isView) {
  if (!options.title) {
    if (isView) {
      options.title = $.i18n('workflow.designer.title.readonly');
    } else {
      options.title = $.i18n('common.design.workflow.label');
    }
  }

  if (!options.buttons || options.buttons.length == 0) {
    if (!isView) {
      options.buttons = [{
        "id": "ok"
      }, {
        "id": "cancel"
      }];
    } else {
      options.buttons = [{
        "id": "close"
      }];
    }
  }
}
/**
 * 第二次打开dialog的时候检查一下窗口是否存在，存在则关闭
 */
function _closeFlashDialogBeforeOpen(tWindow) {
  if (workfowFlashDialog) {
    workfowFlashDialog.isHide = false;
    workfowFlashDialog.close(workfowFlashDialog.index);
  } else {
    if (tWindow && $("#workflow_dialog_workflowDesigner_Id", tWindow.document).size() > 0) {
      tWindow.$("#workflow_dialog_workflowDesigner_Id_mask").remove();
      tWindow.$("#workflow_dialog_workflowDesigner_Id").remove();
    }
  }
}

function tempShowDetailLogDialog(summaryId, processId, showFlag, dataType, affairId) {
  if (dataType == '1') {
    //转储数据
    showDetailLogDialog(summaryId, processId, showFlag, true, affairId);
  } else {
    showDetailLogDialog(summaryId, processId, showFlag, false, affairId);
  }
}; //删除
/**
 * 明细日志 弹出对话框
 * showFlag  初始化时 显示的内容 1:显示处理明细 2:显示流程日志 3:显示催办(督办)日志
 */
function showDetailLogDialog(summaryId, processId, showFlag, isHistoryFlag, affairId) {
  const triggerParams = {summaryId, processId, showFlag, isHistoryFlag, affairId};
  console.log("$.ctp.trigger", "beforeShowDetailLog", triggerParams);
  const sendDevelop = $.ctp.trigger('beforeShowDetailLog', triggerParams);
  if (!sendDevelop) {
    return;
  }

  var checkResult = callBackendMethod("secretAjaxManager", "checkUserSecretLevel", summaryId);

  if (checkResult && checkResult.length > 0) {
    Fiber.message.warning(checkResult);
    return;
  }

  var url = _ctxPath + '/detaillog/detaillog.do?method=showDetailLog&summaryId=' + summaryId + '&processId=' + processId + "&showFlag=" + showFlag + "&isHistoryFlag=" + isHistoryFlag;
  var dialog = $.dialog({
    url: url,
    width: 1040,
    height: 480,
    title: $.i18n('collaboration.sendGrid.findAllLog'),
    //查看明细日志
    targetWindow: getCtpTop(),
    buttons: [{
      text: $.i18n('common.button.close.label'),
      handler: function handler() {
        dialog.close();
      }
    }]
  });
}

function setTrack({ affairId, summaryId }, resetTableData) {
  var dialog = $.dialog({
    targetWindow: getCtpTop(),
    id: 'trackDialog',
    url: _ctxPath + '/collaboration/collaboration.do?method=openTrackDetail&objectId=' + summaryId + '&affairId=' + affairId,
    width: 328,
    height: 100,
    title: $.i18n('common.track.setting'),
    buttons: [{
      id: "trackSubmit",
      text: $.i18n('common.button.ok.label'),
      //确定
      handler: function handler() {
        var returnValue = dialog.getReturnValue();
        if (returnValue && returnValue != null) {
          //返回值到父页面
          resetTableData();
          // if (returnValue == '1' || returnValue == '2') {
          //   $(obj).text($.i18n('common.yes')); //是
          // } else {
          //   $(obj).text($.i18n('common.no')); //否
          // }

          // try {
          //   $("#trackType", window.summaryF.document).val(newTrackType);
          // } catch (e) { }

          dialog.close();
        }
      }
    }, {
      text: $.i18n('common.button.cancel.label'),
      //取消
      handler: function handler() {
        dialog.close();
      }
    }]
  });
};
function takeBack(selectedRows, resetTableData) {
  if (selectedRows.length === 0) {
    Fiber.message.warning($.i18n("collaboration.listDone.selectBack"));
    return;
  }
  if (selectedRows.length > 1) {
    //只能选择一项协同进行取回!
    Fiber.message.warning($.i18n('collaboration.listDone.selectOneBack'));
    return;
  }

  console.log("$.ctp.trigger", "beforeTakeBack", selectedRows);
  const sendDevelop = $.ctp.trigger('beforeTakeBack', selectedRows);
  if (!sendDevelop) {
    return;
  }

  const { affairId, summaryId, workitemId, processId, activityId: nodeId, bodyType, formRecordid } = selectedRows[0];
  let appName = "collaboration";
  const isForm = bodyType == '20';
  if (getAffairState(affairId) != '4') {
    Fiber.message.warning($.i18n('collaboration.listDone.tabkeback.state.js'));
    return;
  }
  const checkResult = callBackendMethod("secretAjaxManager", "checkUserSecretLevel", summaryId);
  if (checkResult && checkResult.length > 0) {
    Fiber.message.warning(checkResult);
    return;
  }
  /**
* 是否允许取回
* 返回值是一个js对象，有以下属性
* canTakeBack 是否允许取回
* state:
*  -1表示程序或数据发生异常,不可以取回
*  0表示正常状态,可以取回
*  1表示当前流程已经结束,不可以取回
*  2表示后面节点任务事项已处理完成,不可以取回
*  3表示当前节点触发的子流程已经结束,不可以取回
*  4表示当前节点触发的子流程中已核定通过,不可以取回
*  5表示当前节点是知会节点,不可以取回
*  6表示当前节点为核定节点,不可以取回
*  7表示当前节点为封发节点，不可以取回
*  9表示当前节点触发的子流程中已审核通过,不可以取回
*/
  const params = `managerMethod=onBeforeValidate4TakeBack&arguments=${JSON.stringify([processId, workitemId, nodeId, _currentUser.id, "", "collaboration"])}`;
  onBeforeValidate4TakeBack(params).then(({ data: validateResult }) => {
    if (validateResult && !validateResult.pass) {
      Fiber.message.warning(validateResult.msg);
      return;
    }
    if (isForm) {
      appName = "form";
    }
    const dialog = $.dialog({
      url: _ctxPath + "/collaboration/collaboration.do?method=showTakebackConfirm",
      width: 400,
      height: 160,
      targetWindow: getCtpTop(),
      title: $.i18n('common.system.hint.label'),
      buttons: [{
        text: $.i18n('common.button.ok.label'),
        handler: async function handler() {

          const dialogValue = dialog.getReturnValue();
          if (dialogValue) {
            const ajaxSubmitFunc = function ajaxSubmitFunc() {
              const takeBackArgs = { affairId, isSaveOpinion: dialogValue != "1" };
              callBackendMethod("colManager", "transTakeBack", takeBackArgs, {
                success(msg) {
                  if (msg == null || msg == "") {
                    resetTableData();
                    //回退成功后，打开该回退协同处理页面
                    let url = _ctxPath + "/collaboration/collaboration.do?method=summary&openFrom=listPending&affairId=" + affairId + (window.CsrfGuard ? CsrfGuard.getUrlSurffix() : "") + "&showTab=true";
                    var a8Top = getA8Top();
                    if (a8Top.isMultipleTabs) {
                      a8Top.openCtpWindow({
                        url
                      });
                    } else {
                      window.open(url);
                    }
                  } else {
                    // 处理页签模式下弹出外层，关闭弹框
                    try {
                      getCtpTop().$.alert(msg);
                    } catch (e) {
                      Fiber.message.warning(msg);
                    }
                  }
                  //撤销后关闭，子页面
                  closeOpenMultyWindow(affairId);
                  dialog.close();
                }
              });
            };
            const idMap = {
              "summaryID": summaryId,
              "affairID": affairId
            };
            console.log("$.ctp.trigger", "beforeDoneTakeBack", idMap);
            const sendDevelop = $.ctp.trigger('beforeDoneTakeBack', idMap);
            if (!sendDevelop) {
              return;
            }
            let paramsOpt = {
              event: "BeforeTakeBack",
              bussinessId: summaryId,
              affairId: affairId,
              processTemplateId: processId,
              processId: processId,
              activityId: nodeId,
              formData: formRecordid,
              appName: appName
            }
            if (!await executeWorkflowBeforeEvent(paramsOpt)) {
              releaseWorkflowByAction(processId, _currentUser.id, 13);
              dialog.close();
              return;
            }
            beforeSubmit(affairId, "takeback", "", dialog, ajaxSubmitFunc, function () {
              releaseWorkflowByAction(processId, _currentUser.id, 13);
              dialog.close();
            });
          }
        }
      }, {
        text: $.i18n('common.button.cancel.label'),
        handler() {
          releaseWorkflowByAction(processId, _currentUser.id, 13);
          dialog.close();
        }
      }],
      closeParam: {
        show: true,
        handler() {
          releaseWorkflowByAction(processId, _currentUser.id, 13);
        }
      }
    });
  });
};
function deleteItems(selectedRows, resetTableData) {
  if (selectedRows.length === 0) {
    Fiber.message.warning($.i18n("collaboration.grid.selectDelete"));
    return;
  }
  let deleteSubjects = "";
  let batchDeleteParams = [];
  let rowItem;

  for (let i = 0; i < selectedRows.length; i++) {
    rowItem = selectedRows[i];
    let param = {
      processId: rowItem.processId,
      affairId: rowItem.affairId,
      objectId: rowItem.summaryId,
      subject: rowItem.subject
    };
    batchDeleteParams.push(param);
    closeOpenMultyWindow(rowItem.affairId, false);
    if (!rowItem.canReMove) {
      if (selectedRows.length == 1) {
        //当前节点权限不可进行删除操作！
        Fiber.message.warning($.i18n('collaboration.alert.CantReMoveOne'));
        // rowItem.checked = false;
        return true;
      } else {
        //根据当前节点权限以下流程不可删除！
        deleteSubjects += "<br>&lt;" + escapeStringToHTML(rowItem.subject) + "&gt;";
        continue;
      }
    }
  }

  if (deleteSubjects.length > 1) {
    Fiber.message.warning($.i18n('collaboration.alert.CantReMove') + deleteSubjects);
    // rowItem.checked = false;
    return true;
  }

  $.confirm({
    // 该操作不能恢复，是否进行删除操作
    'msg': $.i18n('collaboration.confirmDelete'),
    ok_fn: ()=> {
      let secretCheckResult = callBackendMethod("secretAjaxManager", "batchCheckUserSecretLevel", batchDeleteParams);
      let secretCheck = new SecretCheck(secretCheckResult, "delete");
      const affairIdList = secretCheck.getSuccessAffairIds();

      if (affairIdList.length === 0) {
        secretCheck.messageDialog();
        return;
      }
      const pageType = 'finish';
      const params = {
        pageType,
        affairIds: affairIdList.join(","),
        fromMethod: 'listDone'
      };

      callBackendMethod("colManager", "checkCanDelete", params, {
        success:  (flag)=> {
          if ("success" == flag) {
            showLoading()
            let callback =()=>{
              //关闭已经删除了事项打开的子页面
              for (let i = 0; i < affairIdList.length; i++) {
                try {
                  closeOpenMultyWindow(affairIdList[i], false);
                } catch (e) { }
              }

              if (secretCheck && secretCheck.getCancelData().size() !== 0) {
                secretCheck.messageDialog(resetTableData);
                return;
              }
              loadingInstance.close();
              $.messageBox({
                'title': $.i18n('common.system.hint.label'),
                'type': 0,
                'msg': $.i18n('common.delete.success.label'),
                'imgType': 0,
                ok_fn: resetTableData,
                close_fn: resetTableData
              });
            }
            // 循环删除，隔离后台的事务，否则多个流程事务一起提交工作流部分的数据可能会出错
            deleteAffairAjax({ids:affairIdList,pageType,callback})
          } else {
            Fiber.message.warning(flag);
          }
        },
        error: function error(request, settings, e) {
          Fiber.message.warning(e);
        }
      });
    },
    "cancel_fn": function cancel_fn() {
    }
  });
};

function deleteAffairAjax({ids, pageType, callback, count = 0}) {
  const self = this;
  callBackendMethod("colManager", "deleteAffair", pageType, ids[count], {
    success: () => {
      count++;
      if (count < ids.length) {
          deleteAffairAjax({ids, pageType, callback, count})
      } else {
          callback.call(self)
      }
    }
  })
}
//显示流程图
function showFlowChartAJax(
  _affairId, _contextCaseId, _contextProcessId, _templateId, _contextActivityId, bodyType, showHastenButton, dataType
) {

  const triggerParams = {
    affairId: _affairId,
    contextCaseId: _contextCaseId,
    contextProcessId: _contextProcessId,
    templateId: _templateId,
    contextActivityId: _contextActivityId,
    bodyType: bodyType,
    showHastenButton: showHastenButton,
    dataType: dataType
  }
  console.log("$.ctp.trigger", "beforeShowFlowChart", triggerParams);
  const sendDevelop = $.ctp.trigger('beforeShowFlowChart', triggerParams);
  if (!sendDevelop) {
    return;
  }

  //显示流程图
  showFlowChart(_contextCaseId, _contextProcessId, _templateId, _contextActivityId, bodyType, showHastenButton, dataType); //发送点击计数ajax请求

  callBackendMethod("colManager", "showWFCDiagram", _affairId, "listDone");
};
//点击 知会 按钮逻辑 
function informItem(selectedRows,resetTableData){
  console.log("选择的协同数据",selectedRows,resetTableData);
  // 1.判断是否勾选数据 没有勾选数据弹出提示，勾多条数据弹出提示
  if (selectedRows.length === 0) {//请选择要知会的协同!
    Fiber.message.warning($.i18n("collaboration.resource.manage.needSelectData"));
    return;
  }
  if (selectedRows.length > 1) {//只能选择一项协同进行知会
    Fiber.message.warning($.i18n("collaboration.listDone.selectOneInform"));
    return;
  }
  // 外部事项不进行知会  暂不支持外系统事务知会
  const sendDevelop = $.ctp.trigger('beforeDoneInform', selectedRows);
  if (!sendDevelop) {
    return;
  }
  //只勾选一条数据 2.调用接口判断 是否需要弹出选人页面
  const { affairId } = selectedRows[0];
  getValidateInformData({affairId:affairId}).then(res => {
    console.log('当前选择的协同数据是否能知会', res);
    var result = res.data;
    if (result && result.code === 0) {//若是为true就弹出选人界面
      //3.弹出选人页面选择需要知会的数据
      $.selectPeople({
        type: 'selectPeople',
        panels: 'OcipOrganization,Department,BusinessDepartment,Team,Post,Outworker,RelatePeople',
        selectType: 'Member,Department,Team,Account,Post,BusinessDepartment,BusinessAccount',
        text: '单击选择人员',
        showFlowTypeRadio:false,
        isConfirmExcludeSubDepartment: true,
        unallowedSelectEmptyGroup: true,
        minSize: 1,
        excludeElements:",Node|BlankNode,Node|SenderDeptMember,Node|SenderSuperDeptDeptMember,Node|SenderManageDepDeptMember,Node|SenderLeaderDepDeptMember,Node|NodeUserDeptMember,Node|NodeUserSuperDeptDeptMember,Node|NodeUserManageDepDeptMember,Node|NodeUserLeaderDepDeptMember",
        excludeElementsBeyondMemberSize: "Department|3000,Post|3000,Team|3000,Level|3000",
        showFlowText: false,
        showGroupRole: true,
        targetWindow: window.getCtpTop(),
        callback: function(res){
            if (!res || !res.obj || res.obj.length == 0) {
              return;
            }
            var informParams ={
              targetAreaValue:res.value,
              targetAreaText:res.text,
              affairId:affairId
            }
            //4.选择人员后 需要调用知会接口来知会给某个人员
            getDoneInformData(informParams).then(resp=>{
              var informData = resp.data;
              if(informData && informData.code == 0){//知会成功 
                Fiber.message.success($.i18n("govdoc.custom.doneInform.success"))
                resetTableData && resetTableData({ success: false, result: {} });//知会成功之后需要清除选中数据
              }else if(informData && informData.code == 1){//无法知会，当前节点没有知会权限
                Fiber.message.warning($.i18n('govdoc.custom.doneInform.noInform')); 
              }else if(informData && informData.code == 3){//当前流程已终止，不能继续进行知会操作
                Fiber.message.warning($.i18n('govdoc.custom.doneInform.exception.end')); 
              }else if(informData && informData.code == 4){//事项已经被删除，你不能执行该操作
                Fiber.message.warning($.i18n('collaboration.newcoll.check.affair.error')); 
              }else if(informData && informData.code == 5){//当前流程不允许被改变，不能知会。
                Fiber.message.warning($.i18n('govdoc.custom.doneInform.canEdit'));
              }else if(informData && informData.code == 6){//当前流程正在编辑不能操作...
                Fiber.message.warning(informData.message);
              }else{//2或者其他code类型 知会失败
                Fiber.message.warning($.i18n('govdoc.custom.doneInform.fail')); 
              }
            })
        }
      });
    }else if(result && result.code === 2){//无法知会，当前节点没有知会权限
      Fiber.message.warning($.i18n('govdoc.custom.doneInform.noInform'));
    }else if(result && result.code === 3){//当前流程已终止，不能继续进行知会操作
      Fiber.message.warning($.i18n('govdoc.custom.doneInform.exception.end'));
    }else if(result && result.code === 5){//当前流程不允许被改变，不能知会。
      Fiber.message.warning($.i18n('govdoc.custom.doneInform.canEdit'));
    }else{
        Fiber.message.warning($.i18n('govdoc.custom.doneInform.fail')); 
    }
 });
};
export {
  tempShowDetailLogDialog,
  setTrack,
  takeBack,
  deleteItems,
  showFlowChartAJax,
  showDiagram,
  informItem
};
